#!/bin/bash

# 数据库备份脚本
# 用于定期备份MySQL数据库

set -e

# 配置
BACKUP_DIR="/backups"
DATE=$(date +"%Y%m%d_%H%M%S")
BACKUP_FILE="cu_mr_bull_backup_${DATE}.sql"
COMPRESSED_FILE="${BACKUP_FILE}.gz"
RETENTION_DAYS=${BACKUP_RETENTION_DAYS:-30}

# 数据库连接信息
DB_HOST=${MYSQL_HOST:-mysql}
DB_NAME=${MYSQL_DATABASE:-cu_mr_bull_prod}
DB_USER=${MYSQL_USER:-cu_mr_bull}
DB_PASSWORD=${MYSQL_PASSWORD:-password}

# 日志函数
log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1"
}

# 错误处理
error_exit() {
    log "ERROR: $1"
    exit 1
}

# 检查必要的工具
command -v mysqldump >/dev/null 2>&1 || error_exit "mysqldump not found"
command -v gzip >/dev/null 2>&1 || error_exit "gzip not found"

# 创建备份目录
mkdir -p "$BACKUP_DIR" || error_exit "Failed to create backup directory"

log "Starting database backup..."
log "Database: $DB_NAME"
log "Host: $DB_HOST"
log "Backup file: $COMPRESSED_FILE"

# 等待数据库可用
log "Waiting for database to be ready..."
for i in {1..30}; do
    if mysqladmin ping -h"$DB_HOST" -u"$DB_USER" -p"$DB_PASSWORD" --silent; then
        log "Database is ready"
        break
    fi
    if [ $i -eq 30 ]; then
        error_exit "Database not available after 30 attempts"
    fi
    sleep 2
done

# 执行备份
log "Creating database dump..."
mysqldump \
    -h"$DB_HOST" \
    -u"$DB_USER" \
    -p"$DB_PASSWORD" \
    --single-transaction \
    --routines \
    --triggers \
    --events \
    --add-drop-database \
    --databases "$DB_NAME" \
    > "$BACKUP_DIR/$BACKUP_FILE" || error_exit "Database dump failed"

# 压缩备份文件
log "Compressing backup file..."
gzip "$BACKUP_DIR/$BACKUP_FILE" || error_exit "Compression failed"

# 验证备份文件
if [ ! -f "$BACKUP_DIR/$COMPRESSED_FILE" ]; then
    error_exit "Backup file not found after compression"
fi

BACKUP_SIZE=$(du -h "$BACKUP_DIR/$COMPRESSED_FILE" | cut -f1)
log "Backup completed successfully"
log "File: $COMPRESSED_FILE"
log "Size: $BACKUP_SIZE"

# 清理旧备份
log "Cleaning up old backups (older than $RETENTION_DAYS days)..."
find "$BACKUP_DIR" -name "cu_mr_bull_backup_*.sql.gz" -type f -mtime +$RETENTION_DAYS -delete

# 显示当前备份列表
log "Current backups:"
ls -lh "$BACKUP_DIR"/cu_mr_bull_backup_*.sql.gz 2>/dev/null || log "No backup files found"

# 可选：上传到云存储
if [ "$CLOUD_BACKUP_ENABLED" = "true" ] && [ -n "$AWS_S3_BUCKET" ]; then
    log "Uploading backup to S3..."
    if command -v aws >/dev/null 2>&1; then
        aws s3 cp "$BACKUP_DIR/$COMPRESSED_FILE" "s3://$AWS_S3_BUCKET/backups/" || log "WARNING: S3 upload failed"
    else
        log "WARNING: AWS CLI not found, skipping S3 upload"
    fi
fi

log "Backup process completed"
exit 0